package com.rpp.study.base;


import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;

/**
 * @Description 统一返回数据类型
 * @Author rpp
 * @Date 2020/8/30 21:10 下午
 */
@Data
public class LagouResponse<T> implements Serializable {
    private int statusCode;
    private String statusText;
    private T data;
    private String currentTimeMillis;

    public LagouResponse() {
        this.statusCode = BusinessCode.SUCCESS.getCode();
        this.statusText = "success";
        this.data = (T) new HashMap(1);
        this.currentTimeMillis = String.valueOf(System.currentTimeMillis());
    }

    public LagouResponse(int statusCode, String statusText, T t, String currentTimeMillis) {
        this.statusCode = statusCode;
        this.statusText = statusText;
        this.data = t;
        this.currentTimeMillis = currentTimeMillis;
    }

    public LagouResponse(int statusCode, String statusText) {
        this.statusCode = statusCode;
        this.statusText = statusText;
        this.data = (T) new HashMap(1);
        this.currentTimeMillis = String.valueOf(System.currentTimeMillis());
    }

    public LagouResponse(int statusCode, String statusText, T t) {
        this.statusCode = statusCode;
        this.statusText = statusText;
        this.data = t;
        this.currentTimeMillis = String.valueOf(System.currentTimeMillis());
    }

    public static LagouResponse fromBusinessCode(BusinessCode businessCode) {
        return fromBusinessCode(businessCode, new HashMap<>(1));
    }

    public static <T> LagouResponse<T> fromBusinessCode(BusinessCode businessCode, T t) {
        return new LagouResponse(businessCode.getCode(), businessCode.getDesc(), t,
                String.valueOf(System.currentTimeMillis()));
    }

    public static <T> LagouResponse<T> success(T t) {
        return new LagouResponse(BusinessCode.SUCCESS.getCode(), "success", t,
                String.valueOf(System.currentTimeMillis()));
    }

    public static LagouResponse success() {
        return new LagouResponse(BusinessCode.SUCCESS.getCode(), "success", new HashMap<>(1),
                String.valueOf(System.currentTimeMillis()));
    }

    public static LagouResponse error() {
        return fromBusinessCode(BusinessCode.ERROR, null);
    }

    public static LagouResponse error(String message) {
        return new LagouResponse<>(BusinessCode.ERROR.getCode(), message, null);
    }

    public static <T> LagouResponse<T> error(T t) {
        return fromBusinessCode(BusinessCode.ERROR, t);
    }

    public static <T> LagouResponse<T> error(T t, String message) {
        return new LagouResponse<>(BusinessCode.ERROR.getCode(), message, t);
    }

    @JsonIgnore
    public boolean isSuccess() {
        if (BusinessCode.SUCCESS.getCode() == statusCode) {
            return true;
        }
        return false;
    }
}
